import json
import os
from src.entity.CelestialBody import FixedStar


class ConfigLoader:
    """配置加载器，用于从JSON文件加载模拟参数"""

    @staticmethod
    def load_config(config_path):
        """
        从JSON文件加载配置

        :param config_path: 配置文件路径
        :return: 配置字典
        """
        if not os.path.exists(config_path):
            raise FileNotFoundError(f"配置文件不存在: {config_path}")

        with open(config_path, 'r', encoding='utf-8') as f:
            config = json.load(f)

        return config

    @staticmethod
    def create_stars_from_config(config):
        """
        根据配置创建星体对象

        :param config: 配置字典
        :return: 星体对象列表
        """
        stars = []
        for star_config in config['stars']:
            star = FixedStar(
                name=star_config['name'],
                color=star_config['color'],
                mass=star_config['mass'],
                radius=star_config['radius'],
                position=star_config['position'],
                velocity=star_config['velocity']
            )
            stars.append(star)

        return stars

    @staticmethod
    def create_bodies_info_from_config(config):
        """
        根据配置创建绘图元数据

        :param config: 配置字典
        :return: 绘图元数据列表
        """
        bodies_info = []
        for star_config in config['stars']:
            body_info = {
                'name': star_config['name'],
                'color': star_config['color'],
                'radius': star_config['radius'],
                'pos': star_config['position']
            }
            bodies_info.append(body_info)

        return bodies_info

    @staticmethod
    def get_simulation_params(config):
        """
        获取模拟参数

        :param config: 配置字典
        :return: 模拟参数字典
        """
        sim_config = config['simulation']
        return {
            'dt': sim_config['dt'],
            'frames': sim_config['frames'],
            'xlim': tuple(sim_config['xlim']),
            'ylim': tuple(sim_config['ylim']),
            'max_trace': sim_config['max_trace'],
            'max_trail': sim_config['max_trail'],
            'title': sim_config['title'],
            'mp4_path': sim_config['output_file']
        }